import { showLoading, showToast } from "./promise"
import store, { initUserInfo } from '../store/index'

// export const BASE_URL = "http://192.168.3.88:8082"
export const BASE_URL = "https://hilton-api.doradoar.com"
// export const BASE_URL = "http://192.168.3.13:8082"
const TIMEOUT = 15000

export const request = (options) => {
	// console.log(options)
	const mergeOptions = {
		url: `${BASE_URL}${options.url}`,
		data: options.data || {},
		header: {
			"Content-Type": "application/json",
			"X-Client-Type": "MINI_PROGRAM",
			...options.header,
		},
		method: options.method || "POST",
		timeout: options.TIMEOUT || TIMEOUT,
		showLoading: options.showLoading ?? true
	}
	// const userToken = store.state.userToken;
	const userToken = uni.getStorageSync("userToken")
	if (userToken !== null && store.state.tokenInvalid === false) {
		mergeOptions.header.Authorization = `Bearer ${userToken}`
	}
		
	if(mergeOptions.showLoading) {
		showLoading({
			title: "加载中",
			mask: true
		})
	}
	// console.log(mergeOptions)
	return new Promise((resolve, reject) => {
		uni.request({
			...mergeOptions,
			success: (res) => {
				// console.log(res)
				const {code, data, msg} = res.data
        if (code === 401) {
					reject(Object.assign({code, msg}))
					// showToast({
					// 	title: '登录过期，请重新登录',
					// 	icon: "none",
					// })
          store.commit('setUserInfo', initUserInfo)
          store.commit('setUserToken', null)
          return
        }
				if(code !== 200) {
					reject(Object.assign({code, msg}))
					showToast({
						title: msg,
						icon: "none",
					})
          return
				}
				resolve(Object.assign({code, data, msg}))
			},
			fail: (err) => {
				// console.log(err)
				showToast({
					title: err.errMsg,
					icon: "none",
				})
				reject(err)
				// return
			},
			complete: () => {
				if(mergeOptions.showLoading) {
					uni.hideLoading()
				}
			}
		})
	})
}
